<template>
  <div :id="editorId" class="wangeditorBox">
    <div ref="editorElem" style="text-align:left"
      @mousedown="mouseDowndragElement"
      @mousemove="mouseMoveElement"
      @dblclick="doubleclickHandle"></div>
    <input style="display:none;" type="file" :id="'richtxt-reupload-image-'+editorId" name="files">
  </div>
</template>
<script>
import E from "wangeditor";
// import wangeditorEmotiones from './wangeditor.js'
import wangeditorEmotiones from '@/js/operation_manage/wangeditor.js'
var g_preimage=null;
export default {
  name: "editorElem",
  data() {
    return {
      editor: null,
      editorContent: ""
    };
  },
  props: ["catchData", "content",'editorId','contenteditable'], // 接收父组件的方法
  watch: {
    // content() {
    //   this.editor.txt.html(this.content);
    // }
  },
  methods: {
    /**全屏功能 */
    initFullScreen() {
      let self = this;
      E.fullscreen = {
        // editor create之后调用
        init: function(editorSelector) {
          let fulls=$(editorSelector + " .w-e-toolbar").find('._wangEditor_btn_fullscreen');
          if(fulls.length==0){
            $(editorSelector + " .w-e-toolbar")
              .append(`<div class="w-e-menu" title="全屏" style="">
              <a class="_wangEditor_btn_fullscreen" fullscreen="1"><i class="el-icon-view"></i></a></div>`);
            $("._wangEditor_btn_fullscreen").on("click", function(d) {
              // console.log(d)
              let ele = d.currentTarget;
              if (ele.getAttribute('fullscreen') == "1") {
                self.fullscreenAtivate(true);
                ele.setAttribute('fullscreen','0')
              } else {
                self.fullscreenAtivate(false);
                ele.setAttribute('fullscreen','1')
              }
            });
          }
        }
      };
      E.fullscreen.init("#"+this.editorId);
    },
    /**全屏*/
    fullscreenAtivate(flg) {
      this.wangeditorFullScreen(flg);
      return;
      if (flg) {
        let el = document.documentElement;
        let rfs =
          el.requestFullScreen ||
          el.webkitRequestFullScreen ||
          el.mozRequestFullScreen ||
          el.msRequestFullScreen;
        if (rfs) {
          //typeof rfs != "undefined" && rfs
          rfs.call(el);
        } else if (typeof window.ActiveXObject != "undefined") {
          //for IE，这里其实就是模拟了按下键盘的F11，使浏览器全屏
          let wscript = new ActiveXObject("WScript.Shell");
          if (wscript != null) {
            wscript.SendKeys("{F11}");
          }
        }
      } else {
        let el = document;
        let cfs =
          el.cancelFullScreen ||
          el.webkitCancelFullScreen ||
          el.mozCancelFullScreen ||
          el.exitFullScreen;
        if (cfs) {
          //typeof cfs != "undefined" && cfs
          cfs.call(el);
        } else if (typeof window.ActiveXObject != "undefined") {
          //for IE，这里和fullScreen相同，模拟按下F11键退出全屏
          let wscript = new ActiveXObject("WScript.Shell");
          if (wscript != null) {
            wscript.SendKeys("{F11}");
          }
        }
      }
    },
    /**编辑器全屏 */
    wangeditorFullScreen(flg){
      // console.log(this.$refs.editorElem)
      if(flg){
        $(this.$refs.editorElem).addClass('fullscreen-editor');
      }
      else{
        $(this.$refs.editorElem).removeClass('fullscreen-editor');
      }
    },
    /**清空内容按钮 */
    initClearFunc(){
      let self = this;
      E.clearAllContent = {
        // editor create之后调用
        init: function(editorSelector) {
          let fulls=$(editorSelector + " .w-e-toolbar").find('._wangEditor_btn_clearAll');
          if(fulls.length==0){
            $(editorSelector + " .w-e-toolbar")
              .append(`<div class="w-e-menu" title="清空" style="">
              <a class="_wangEditor_btn_clearAll" fullscreen="1"><i class="el-icon-delete"></i></a></div>`);
            $("._wangEditor_btn_clearAll").on("click", function(d) {
              // self.editor.txt.clear();
              self.editor.cmd.do('selectAll', null);
              self.editor.cmd.do('delete', null);
            });
          }
        }
      };
      E.clearAllContent.init("#"+this.editorId);
    },
    /**拖拽修改图片大小：改变鼠标图标 */
    mouseMoveElement(e){
      if(!this.contenteditable)return;
      let targetDiv= e.target; 
      if(targetDiv.nodeName!='IMG'||this._imageResizeing)return;
      if($('.w-e-text').find(targetDiv).length==0)return;
      targetDiv.title='双击图片重新上传';
      //元素边界确定
      let scrollTop=$('#'+this.editorId+' .w-e-text').scrollTop();
      let R0 = this.getRealOffset(targetDiv,'offsetLeft') + targetDiv.offsetWidth;
      let B0 = this.getRealOffset(targetDiv,'offsetTop') + targetDiv.offsetHeight-scrollTop;
      //范围确定
      let dis=20;
      let areaR = ((e.clientX > R0-dis)&&(e.clientX < R0+dis));
      let areaB = ((e.clientY > B0-dis)&&(e.clientY < B0+dis));
      //右侧范围
      if(areaR){
          targetDiv.style.cursor = 'e-resize';
      }
      //下侧范围
      if(areaB){
          targetDiv.style.cursor = 's-resize';
      }    
      //右下范围
      if(areaR && areaB){
          targetDiv.style.cursor = 'se-resize';
      }    
      //中间范围    
      if( !areaR  && !areaB){
          targetDiv.style.cursor = 'default';
      }
    },
    /**拖拽修改图片大小：拖拽功能 */
    mouseDowndragElement(e){
      if(!this.contenteditable)return;
      let self=this;
      let targetDiv= e.target; 
      if(targetDiv.nodeName!='IMG')return;
      targetDiv.setAttribute('draggable',false);
      window.getSelection().removeAllRanges();
      this._imageResizeing=true;
      
      let firstX = e.clientX;  //获取第一次点击的横坐标
      let firstY = e.clientY;   //获取第一次点击的纵坐标
      let width = targetDiv.offsetWidth;  //获取到元素的宽度
      let height = targetDiv.offsetHeight;  //获取到元素的高度
      //判断方向结束
      document.onmousemove = function(e){
          switch(targetDiv.style.cursor)
          {
              case "e-resize":
                  targetDiv.style["width"] = width+(e.clientX-firstX)+"px";
                  break;
              case "s-resize":
                  targetDiv.style["height"] = height+(e.clientY-firstY)+"px";
                  break;
              case "se-resize":
                  targetDiv.style["height"] = height+(e.clientY-firstY)+"px";
                  targetDiv.style["width"] = width+(e.clientX-firstX)+"px";
                  break;
          }
      }
      document.onmouseup = function(){
        self._imageResizeing=false;
        document.onmousemove = null;
      }

    },
    /**父组件传递新的内容并赋值 */
    initContent(text){
      this.editor.txt.html(text);
    },
    /**双击重新上传图片 */
    doubleclickHandle(e){
      if(!this.contenteditable)return;
      let targetDiv= e.target; 
      if(targetDiv.nodeName!='IMG'||this._imageResizeing)return;
      if($('.w-e-text').find(targetDiv).length==0)return;
      g_preimage=targetDiv;
      document.querySelector('#richtxt-reupload-image-'+this.editorId).click();
    },
    /**获取元素相对于body的定位 */
    getRealOffset(obj,direction){
      var offsetDir = direction;
      var realNum = obj[offsetDir];
      var positionParent = obj.offsetParent;  //获取上一级定位元素对象
      while(positionParent != null){
        realNum += positionParent[offsetDir];
        positionParent = positionParent.offsetParent;
      }
      return realNum;
    },
    /**获取微博表情 */
    getweiboemotions(){
      // console.log(wangeditorEmotiones)
      let result={};
      let notinclude=['复仇者联盟','米奇米妮'];
      for(let i=0;i<wangeditorEmotiones.wangeditorEmotiones.length;i++){
        let row=wangeditorEmotiones.wangeditorEmotiones[i];
        let category=row.category;
        if(notinclude.includes(category))continue;
        if(result.hasOwnProperty(category))
        {
          result[category].push({
            alt:row.value,
            src:row.icon
          });
        }
        else{
          result[category]=[];
        }
      }
      let emotions=[];
      for(let name in result){
        emotions.push({
          title: name,
          type: 'image',
          content:result[name]
        });
      }
      return emotions;
    },
    /**返回当前编辑器内的HTML */
    callBackHtml(){
      return this.editor.txt.html();
    }
  },
  mounted() {
    if(!this.contenteditable){
      this.editor = new E(this.$refs.editorElem);
      this.editor.customConfig.zIndex = 29;
      this.editor.customConfig.menus=['undo',  // 撤销
        'redo',  //
      ];
      this.editor.create(); // 创建富文本实例
      this.editor.txt.html(this.content);
      this.editor.$textElem.attr('contenteditable', this.contenteditable);
    }
    else
    {
      //重新上传图片
      let self=this;
      document.getElementById("richtxt-reupload-image-"+this.editorId).addEventListener('change',function(e){
        var files =this.files;
        let file = files[0];
        var dx =(file.size/1024)/1024;
        if(dx>2){
          self.$message({
            message: '单张图片最大不能超过2M，请重新选择图片！',
            type: 'warning'
          });
          g_preimage=null;
          return;
        }
        if(!g_preimage){
          self.$message({
            message: '未选择图片！',
            type: 'warning'
          });
          return;
        }
        let filedata = new FormData(); //创建form对象
        filedata.append("file", file, file.name); //通过append向form对象添加数据
        filedata.append("content", "officialWebsite"); //添加form表单中其他数据
        api.uploadFile(filedata).then(function(d) {
          if (d.result = "操作成功") {
            let cloneimg=$(g_preimage).clone()[0];
            cloneimg.src=d.url;
            self.editor.cmd.do('insertHTML', cloneimg.outerHTML);
            g_preimage=null;
          }
        });
      });
      this.editor = new E(this.$refs.editorElem);
      this.editor.customConfig.onchange = html => {
        this.editorContent = html;
        this.catchData(this.editorContent); // 把这个html通过catchData的方法传入父组件
      };
      // this.editor.customConfig.uploadImgServer = "你的上传图片的接口";
      // this.editor.customConfig.uploadFileName = "你自定义的文件名";
      this.editor.customConfig.uploadImgMaxSize = 2 * 1024 * 1024;//图片大小m
      this.editor.customConfig.uploadImgMaxLength = 3;//单次上传最大数量
      this.editor.customConfig.zIndex = 29;
      this.editor.customConfig.menus = [
        // 菜单配置
        'undo',  // 撤销
        'redo',  //
        'head',  // 标题
        'bold',  // 粗体
        'fontSize',  // 字号
        'fontName',  // 字体
        'italic',  // 斜体
        'underline',  // 下划线
        'strikeThrough',  // 删除线
        'foreColor',  // 文字颜色
        'backColor',  // 背景颜色
        'link',  // 插入链接
        'list',  // 列表
        'justify',  // 对齐方式
        'quote',  // 引用
        'emoticon',  // 表情
        'image',  // 插入图片
        'table',  // 表格
        'video',  // 插入视频
        // 'code',  // 插入代码
        
      ];
      // 表情面板可以有多个 tab ，因此要配置成一个数组。数组每个元素代表一个 tab 的配置
      let emotions=this.getweiboemotions();
      this.editor.customConfig.emotions = emotions;
      //自定义图片上传
      this.editor.customConfig.customUploadImg = function(files, insert) {
        // files 是 input 中选中的文件列表
        // insert 是获取图片 url 后，插入到编辑器的方法
        // console.log(files)
        for (let i = 0; i < files.length; i++) {
          let file = files[i];
          let filedata = new FormData(); //创建form对象
          filedata.append("file", file, file.name); //通过append向form对象添加数据
          filedata.append("content", "officialWebsite"); //添加form表单中其他数据
          api.uploadFile(filedata).then(function(d) {
            if ((d.result = "操作成功")) {
              insert(d.url);
            }
          });
        }
      };
      // 自定义处理粘贴的文本内容
      this.editor.customConfig.pasteTextHandle = function (content) {
          // content 即粘贴过来的内容（html 或 纯文本），可进行自定义处理然后返回
          content=content.replace(/<!--(.|[\r\n])*?-->/g,"");//去掉注释内容
          return content;
      }
      this.editor.create(); // 创建富文本实例
      this.editor.txt.html(this.content);
      this.initClearFunc();
      this.initFullScreen();
      // let isedite=true;
      // if(this.contenteditable)isedite=false;
      this.editor.$textElem.attr('contenteditable', this.contenteditable);

      //粘贴测试
      //复制单张图片时可从剪切板读取到文件对象；复制图片+文字内容时，剪切板不是文件对象，无法获取图片文件
      // this.editor.$textElem.on('paste',function(e){
      //   var clipboardData = e.clipboardData || e.originalEvent && e.originalEvent.clipboardData || {};
      //   var items = clipboardData.items;
      //   console.log(clipboardData);
      // });

      //图片浮动设置
      $('#'+this.editor.imgMenuId).on('click',function(d){
        if(!self.editor._selectedImg||self.editor._selectedImg===0)return;
        $('.w-e-panel-tab-content>div').prepend(`<div class="w-e-button-container" style="border-bottom:1px solid #f1f1f1;padding-bottom:5px;margin-bottom:5px;">
            <span style="float:left;font-size:14px;margin:4px 5px 0 5px;color:#333;">图片位置：</span>
            <button class="left weditor-floatImg" style="margin-right:0;padding: 5px 5px;">默认</button>
            <button class="left weditor-floatImg" style="margin-right:0;padding: 5px 5px;">左浮动</button>
            <button class="left weditor-floatImg" style="margin-right:0;padding: 5px 5px;">居中</button>
            <button class="left weditor-floatImg" style="margin-right:0;padding: 5px 5px;">右浮动</button>
            </div>`
        );
        $('.weditor-floatImg').on('click',function(d){
          // console.log(self.editor);
          let position=d.currentTarget.innerText;
          // let cloneimg=$(self.editor._selectedImg).clone();
          // self.editor.cmd.do('insertHTML', cloneimg.outerHTML);
          if(position=='左浮动'){
            self.editor._selectedImg.css('float','left');
            self.editor._selectedImg.css('margin','0px 10px 0px 0');
            // cloneimg.css('float','left');
            // cloneimg.css('margin','0px 10px 0px 0');self.editor.cmd.do('insertHTML', cloneimg[0].outerHTML);
            self.editor.cmd.do('justifyFull', null);
          }
          else if(position=='右浮动'){
            self.editor._selectedImg.css('float','right');
            self.editor._selectedImg.css('margin','0px 0 0px 10px');
            // cloneimg.css('float','right');
            // cloneimg.css('margin','0px 0 0px 10px');self.editor.cmd.do('insertHTML', cloneimg[0].outerHTML);
            self.editor.cmd.do('justifyFull', null);
          }
          else if(position=='居中'){
            self.editor._selectedImg.css('float','unset');
            self.editor._selectedImg.css('margin','unset');
            // cloneimg.css('float','unset');
            // cloneimg.css('margin','unset');self.editor.cmd.do('insertHTML', cloneimg[0].outerHTML);
            self.editor.cmd.do('justifyCenter', null);
          }
          else{
            self.editor._selectedImg.css('float','unset');
            self.editor._selectedImg.css('margin','unset');
            // cloneimg.css('float','unset');
            // cloneimg.css('margin','unset');self.editor.cmd.do('insertHTML', cloneimg[0].outerHTML);
            self.editor.cmd.do('justifyLeft', null);
          }
          try{self.editor.change();self.editor.menus.menus.image.panel.hide();}
          catch(err){}

        });
      });
    }
  }
};
</script>
<style lang="scss">
.wangeditorBox {
  height: 100%;
  .w-e-toolbar{
    flex-wrap: wrap !important;
    font-size: 0.14rem !important;
  }
  .w-e-toolbar .w-e-droplist {
    background: #d0cfcf !important;
  }
  .w-e-toolbar .w-e-droplist .w-e-dp-title{
    color: black !important;
  }
  .w-e-text-container {
    height: 5rem !important;
    
    .w-e-text {
      overflow-x: hidden;
      overflow-y: auto;
      img{
        user-select:none;
      }
      img:hover{
        box-shadow: unset;
      }
    }
    .w-e-emoticon-container{
      img{
        width: 0.3rem;
        height: auto;
      }
    }
    
    // 滚动条
    .w-e-text::-webkit-scrollbar {
      width: 0.05rem;
      height: 0.1rem;
    }
    .w-e-text::-webkit-scrollbar-thumb {
      border-radius: 0.5rem;
      background: #bbbbbb;
    }
    .w-e-text::-webkit-scrollbar-track {
      background: #f2f6fc;
    }
    // 滚动条
    .w-e-panel-tab-content::-webkit-scrollbar {
      width: 0.05rem;
      height: 0.1rem;
    }
    .w-e-panel-tab-content::-webkit-scrollbar-thumb {
      border-radius: 0.5rem;
      background: #bbbbbb;
    }
    .w-e-panel-tab-content::-webkit-scrollbar-track {
      background: #f2f6fc;
    }
  }
  .fullscreen-editor {
    position: fixed !important;
    width: 100% !important;
    height: 100% !important;
    left: 0px !important;
    top: 0px !important;
    background-color: white;
    z-index: 9999;
  }

  .fullscreen-editor .w-e-text-container {
    width: 100% !important;
    height: 95% !important;
  }
}
</style>